from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from django.db.models import Prefetch
from . import models, corporateSer

from corporateRecruitment import models, corporateSer


# Create your views here.
class CorporationRecruitmentView(ListAPIView):
    queryset = models.recruiterManagement.objects.all()
    serializer_class = corporateSer.CorporatePositionSerializer


class changeCorporationRecruitmentView(APIView):
    def get(self, request):
        id = request.query_params.get('id')
        data = models.recruiterManagement.objects.filter(recruitmentPositions=id)

        if not data:
            return Response({"code": 200, "msg": "数据为空"})
        ser = corporateSer.CorporatePositionSerializer(data, many=True)
        return Response({"data": ser.data, "code": 200, "msg": "查询成功"})


class RecruiterViewSet(ModelViewSet):
    queryset = models.recruiterManagement.objects.all()
    serializer_class = corporateSer.CorporatePositionSerializer


class CompanyRecruiterListAPIView(ListAPIView):
    queryset = models.recruiterManagement.objects.all()
    serializer_class = corporateSer.CorporatePositionSerializer

    def get_queryset(self):
        company_id = self.request.query_params.get('company_id')
        return models.recruiterManagement.objects.filter(position_id=company_id)


class JobRecruiterViewSet(ModelViewSet):
    queryset = models.jobRecruiter.objects.all()
    serializer_class = corporateSer.JobRecruiterSerializer


class JobCategoryViewSet(ModelViewSet):
    queryset = models.jobCategory.objects.filter(parent__isnull=True)
    serializer_class = corporateSer.JobCategorySerializer


class jobCategoryListAPIView(ListAPIView):
    # 1. 只查询一级分类（parent为NULL）
    # 2. 预加载所有层级的子分类（递归预加载，无N+1查询）
    queryset = models.jobCategory.objects.filter(
        parent__isnull=True  # 一级分类：父级为空
    ).prefetch_related(
        # 预加载一级分类的子分类（二级），并嵌套预加载二级分类的子分类（三级）
        Prefetch(
            'jobcategory_set',  # 一级分类的子分类反向关联名
            queryset=models.jobCategory.objects.prefetch_related(
                # 预加载二级分类的子分类（三级）
                'jobcategory_set'
            )
        )
    )
    serializer_class = corporateSer.JobCategorySerializer  # 关联优化后的序列化器
